import { Base } from "../../utils/base";
class Cart extends Base{

  constructor() {
    super();
    this._storageKeyName = 'cart'
  }

  add(item, counts) {
    var cartData = this.getCartDataFromLocal();
    var isHadInfo = this._isHasThatOne(item.id, cartData);
    if (isHadInfo.index == -1) {
      item.counts = counts;
      item.checkStatus = true;  //默认在购物车中为选中状态
      cartData.push(item);
  }
  //已有商品
  else {
      cartData[isHadInfo.index].counts += counts;
  }
    this.execSetStorageSync(cartData);  //更新本地缓存
    return cartData;
  }
   /*本地缓存 保存／更新*/
   execSetStorageSync(data) {
    wx.setStorageSync(this._storageKeyName, data);
 }

  //读取缓存
  getCartDataFromLocal(flag) {
    var res = wx.getStorageSync(this._storageKeyName);
    if (!res) {
        return [];
    }
    //在下单的时候过滤不下单的商品，
    if (flag) {
      var newRes = [];
      for (let i = 0; i < res.length; i++) {
          if (res[i].checkStatus) {
              newRes.push(res[i]);
          }
      }
      res = newRes;
  }
  return res;
  }

   /**
    *  加入到购物车
    * 如果之前没有样的商品，则直接添加一条新的记录， 数量为 counts
    * 如果有，则只将相应数量 + counts
    * @params:
    * item - {obj} 商品对象,
    * counts - {int} 商品数目,
     */
    _isHasThatOne(id, arr) {
      var item,
          result = { index: -1 };
      for (let i = 0; i < arr.length; i++) {
          item = arr[i];
          if (item.id == id) {
              result = {
                  index: i,
                  data: item
              };
              break;
          }
      }
      return result;
  }

     /*
  * 增加商品数目
  * 
  */
    addCounts(id) {
      this._changeCounts(id, 1);
    }

    /*
    * 购物车减
    *
    */
    cutCounts(id) {
      this._changeCounts(id, -1);
    }

        /*
   ** 修改商品数目
   ** params:
   ** id - {int} 商品id
   **counts -{int} 数目
   **
   */
  _changeCounts(id, counts) {
    var cartData = this.getCartDataFromLocal(),
        hasInfo = this._isHasThatOne(id, cartData);
    if (hasInfo.index != -1) {
        if (hasInfo.data.counts >= 1) {
            cartData[hasInfo.index].counts += counts;
        }
    }
    this.execSetStorageSync(cartData);  //更新本地缓存
};

// 删除
delete(ids) {
  if (!(ids instanceof Array)) {
      ids = [ids];
  }
  var cartData = this.getCartDataFromLocal();
  for (let i = 0; i < ids.length; i++) {
      var hasInfo = this._isHasThatOne(ids[i], cartData);
      if (hasInfo.index != -1) {
          cartData.splice(hasInfo.index, 1);  //删除数组某一项
      }
  }
  this.execSetStorageSync(cartData);
}

/**
     * 计算购物车下商品数量
     * @returns 
     */
    getCartTotalCounts(flag) {
      var data = this.getCartDataFromLocal();
      var counts = 0;
      for (let i = 0; i < data.length; i++) {
          if (data[i].selectStatus) {
              counts += data[i].counts;
          } else {
              counts += data[i].counts;
          }
      }
      return counts;
  }


}
export{Cart}